<?php

namespace app\admin\controller;

use app\models\{Region, User as Users, UserLevel, Coupon, Address, Agent, IntergralLog, Product, MoneyLog,Order};
use think\Db;
use think\Validate;

class User extends Base
{

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Users();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['nickName|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=',  $post['type']];
            }
            if (!empty($post['id'])) {
                $where[] = ['id', '=',  $post['id']];
            }
            if (!empty($post['mobile'])) {
                $user_id = (new Address())->where('mobile|name', $post['mobile'])->column('user_id') ?? [];
                $where[] = ['id', 'in',  $user_id];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $result) {
                $address = (new Address())->where('user_id', $result['id'])->order('is_default desc')->find() ?? [];
                if (!empty($address)) {
                    $address_name = getdrees($address['street'], 2);
                    $address['province_name'] = $address_name['province'];
                    $address['city_name'] = $address_name['city'];
                    $address['area_name'] = $address_name['area'];
                    $address['street_name'] = $address_name['street'];
                }
                $result['user_name'] = (new Users())->where(['id' => $result['pid']])->value('nickName') ?? '用户';
                if ($result['pid'] == 0) {
                    $result['user_name'] = '无推荐人';
                }
                $result['level_name'] = (new UserLevel())->where(['level' => $result['level']])->value('name');
                $result['address'] = $address;
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }


    public function interlog()
    {
        if ($this->request->isAjax()) {
            $model = new IntergralLog();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $user_id = input('id/d') ?? 0;
            $where = array();
            $where[] = ['user_id', '=', $user_id];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function moneylog()
    {
        if ($this->request->isAjax()) {
            $model = new MoneyLog();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $user_id = input('id/d') ?? 0;
            $where = array();
            $where[] = ['user_id', '=', $user_id];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function money_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'moneys' => 'require|gt:0',
                'type' => 'require|in:1,2',
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
                'moneys.require' => '金额不能为空',
                'moneys.gt' => '金额必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $data['desc'] = empty($data['desc']) ? '资产变更' : $data['desc'];
            if ($data['type'] == 1) {
                $money = abs($data['moneys']);
            } else {
                $money = -abs($data['moneys']);
            }
            $user = (new Users())->where('id', $data['id'])->find();
            Db::startTrans();
            try {
                (new Users())->MondyEdit($user['id'], $user['money'], $money, 4, 0, $data['desc']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
    }

    public function coupon()
    {
        if ($this->request->isAjax()) {
            $model = new Coupon();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $user_id = input('user_id/d', 0);
            $promo = input('promo/d', 0);
            $keyid = input('keyid/d', 0);
            $where = array();
            if (!empty($user_id)) {
                $where[] = ['user_id', '=', $user_id];
            }
            if (!empty($keyid)) {
                $where[] = ['keyid', '=', $keyid];
            }
            $count = $model->where($where);
            if (!empty($promo)) {
                $count = $count->where("FIND_IN_SET('" . $promo . "',promo)");
            }
            $count = $count->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("endtime asc")->limit($limit)->page($page);
            if (!empty($promo)) {
                $list = $list->where("FIND_IN_SET('" . $promo . "',promo)");
            }
            $list = $list->select();
            foreach ($list as $result) {
                $user = (new Order())->order('id desc')->where('user_id',$result['user_id'])->find();
                if(empty($user)){
                    $user = (new Address())->order('is_default desc')->where('user_id',$result['user_id'])->find();
                }
                $result['name'] = $user['name'] ?? '';
                $result['mobile'] = $user['mobile'] ?? '';
                $result['shop_name'] = '--';
                $result['product_name'] = '--';
                if ($result['agentid'] > 0) {
                    $result['shop_name'] = (new Agent())->where('id', $result['agentid'])->value('accounts');
                }
                if ($result['types'] == 2) {
                    $lists['title'] = '平台抵扣券';
                    $typess = explode(',', $result['productid']);
                    $result['text'] = '适用于:';
                    $text = '';
                    foreach ($typess as $k => $types) {
                        $type_text = config()['config']['type'][$types] ?? '';
                        if (!empty($text) && empty($typess[$k + 1])) {
                            $text .= $type_text . ',最终是否可抵扣以结算页面抵扣为准。有效期至:' . $result['endtime'];
                        } elseif (!empty($text)) {
                            $text .= '、' . $type_text;
                        } else {
                            $text .= $type_text;
                        }
                    }
                    $result['text'] = $result['text'] . $text;
                }
                $result['usernick'] = (new Users())->where('id', $result['user_id'])->value('nickName');
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function couponel()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['code' => 1, 'msg' => '请选择删除项目']);
            }
            $banner = (new Coupon())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['code' => 1, 'msg' => '优惠券不存在，请重试']);
            }
            if ($banner['status'] != 1) {
                return json(['code' => 1, 'msg' => '优惠券已作废']);
            }
            $res = (new Coupon())->where('id', $id)->update(['status' => 2, 'remark' => $banner['remark'] . '|管理员作废']);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        }
    }

    public function sendcoupon()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2',
                'getmoney' => 'require|gt:0',
                'money' => 'require|gt:0',
                'user_id' => 'require',
                'days' => 'require|gt:0',
            ], [
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
                'getmoney.require' => '可用金额不能为空',
                'getmoney.gt' => '可用金额必须大于0',
                'money.require' => '抵扣金额不能为空',
                'money.gt' => '抵扣金额必须大于0',
                'user_id.require' => '用户ID不能为空',
                'days.require' => '有效期不能为空',
                'days.gt' => '有效期必须大于0',

            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            // if ($data['getmoney'] < $data['money']) {
            //     return json(['code' => 1, 'msg' => '抵扣金额不能超过可用金额']);
            // }
            if ($data['type'] == 2 && empty($data['agentid'])) {
                return json(['code' => 1, 'msg' => '代理ID不能为空']);
            }
            $data['endtime'] = date('Y-m-d H:i:s', time() + $data['days'] * 86400);
            $res = (new Coupon())->allowfield(true)->save($data);
            if ($res) {
                return json(['code' => 200, 'msg' => '编辑成功']);
            }
            return json(['code' => 200, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('user_id/d', 0);
            $agent = (new Agent())->where(['status' => [1, 2]])->select();
            return view('', [
                'agent' => $agent,
                'id' => $id
            ]);
        }
    }


    public function user_level()
    {

        if ($this->request->isAjax()) {
            $model = new UserLevel();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("level desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function user_level_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['coupon'] = json_encode($data['parpam'] ?? [], true);
            $data['coupons'] = json_encode($data['coupons'] ?? [], true);
            $res = (new UserLevel())->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '编辑成功']);
            }
            return json(['code' => 200, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new UserLevel())->where(['id' => $id])->find();
            if ($row) {
                $row['coupon'] = json_decode($row['coupon'], true);
                $row['coupons'] = json_decode($row['coupons'], true);
            }
            return view('', [
                'row' => $row
            ]);
        }
    }
}
